package com.wanxi.dao.Impl;

import com.wanxi.dao.NavDao;
import com.wanxi.model.Nav;
import com.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NavDaoImpl implements NavDao {
    @Override
    public List<Nav> findAllNav() {
        List<Nav> list=new ArrayList<>();
        String sql="select * from nav";
        ResultSet query = JDBC.query(sql);
        try{
            while (query.next()){
                Nav n=new Nav();
                n.setId(query.getInt("id"));
                n.setNavName(query.getString("navName"));
                n.setRemark(query.getString("remark"));
                n.setEnable(query.getInt("enable"));
                n.setUpdateTime(query.getTimestamp("updateTime"));
                n.setCreateTime(query.getTimestamp("createTime"));
                n.setNavHref(query.getString("navHref"));
                list.add(n);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public Nav findNavById(Nav nav) {
        Nav n=new Nav();
        String sql="select * from nav where id="+nav.getId();
        ResultSet query = JDBC.query(sql);
        try {
            while (query.next()){
                n.setId(query.getInt("id"));
                n.setNavName(query.getString("navName"));
                n.setNavHref(query.getString("navHref"));
                n.setEnable(query.getInt("enable"));
                n.setUpdateTime(query.getTimestamp("updateTime"));
                n.setCreateTime(query.getTimestamp("createTime"));
                n.setRemark(query.getString("remark"));
                return n;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public int updateEnable(Nav nav) {
        String sql="update nav set enable="+nav.getEnable()+",updateTime=(select now()) where id="+nav.getId();
        return JDBC.update(sql);
    }

    @Override
    public int addNav(Nav nav) {
        String sql="insert into nav(navName,navHref,enable,createTime,updateTime,remark) values('"+nav.getNavName()
                +"','"+nav.getNavHref()
                +"','"+nav.getEnable()
                +"',(select now()),(select now()),'"+nav.getRemark()+"')";
        return JDBC.update(sql);
    }

    @Override
    public int updateNav(Nav nav) {
        String sql="update nav set navName='"+nav.getNavName()
                +"',navHref='"+nav.getNavHref()
                +"',enable="+nav.getEnable()
                +",remark='"+nav.getRemark()
                +"',updateTime=(select now()) where id="+nav.getId();
        return JDBC.update(sql);
    }

    @Override
    public int delete(Nav nav) {
        String sql="delete from nav where id="+nav.getId();
        return JDBC.update(sql);
    }
}
